import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from '../utils/axios'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const username = ref(localStorage.getItem('username') || '')

  // 初始化状态
  const initializeStore = () => {
    token.value = localStorage.getItem('token') || ''
    username.value = localStorage.getItem('username') || ''
  }

  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const clearToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  // 添加获取用户信息的方法
  const fetchUserInfo = async () => {
    try {
      const response = await axios.get('/users/profile')
      userInfo.value = response.data
      return response.data
    } catch (error) {
      console.error('Error fetching user info:', error)
      throw error
    }
  }

  const login = async (loginData) => {
    try {
      console.log('Sending login request with data:', loginData)
      const response = await axios.post('/auth/login', loginData)
      console.log('Login response:', response.data)
      
      if (response.data && response.data.token) {
        token.value = response.data.token
        username.value = response.data.username
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('username', response.data.username)
        localStorage.setItem('avatar', response.data.avatar)
        return true
      } else {
        ElMessage.error('登录响应格式错误')
        return false
      }
    } catch (error) {
      console.error('Login error:', error)
      ElMessage.error(error.response?.data?.message || '登录失败')
      return false
    }
  }

  const logout = async () => {
    try {
      await axios.post('/auth/logout')
    } catch (error) {
      console.error('Error during logout:', error)
    } finally {
      userInfo.value = null
      clearToken()
    }
  }

  return {
    userInfo,
    token,
    username,
    setToken,
    clearToken,
    fetchUserInfo,
    login,
    logout,
    initializeStore
  }
}) 